<?php

/**
 * Base project form.
 * 
 * @package    sf_sandbox
 * @subpackage form
 * @author     Your name here 
 * @version    SVN: $Id: BaseForm.class.php 20147 2009-07-13 11:46:57Z FabianLange $
 */
class BaseForm extends sfFormSymfony {

    public function setup() {
        sfProjectConfiguration::getActive()->loadHelpers('I18N');
        $this->disableCSRFProtection(); // by default enabled...
    }

    public function setCustomFormatter($formatter_class = 'StarFormFormatter') {
        $decorator = new $formatter_class($this->widgetSchema, $this->validatorSchema);
        $this->widgetSchema->addFormFormatter('custom', $decorator);
        $this->widgetSchema->setFormFormatterName('custom');
    }

    /**
     * get a display value for the field
     *
     * @param sfFormField $form_field
     * @param string $f_value if passed it will be used as a value for this field
     * @return string field value as a string
     */
    public static function getShowValue(sfFormField $form_field, $f_value = null) {

        $class = get_class($form_field->getWidget());
        $return_val = '';

        if (is_null($f_value)) {
            $f_value = $form_field->getValue();
        }
        switch ($class) {
            case 'sfWidgetFormInputCheckbox':
                $return_val = $f_value == true ? I18nUtilities::__('Yes') : I18nUtilities::__('No');
                break;

            case 'sfWidgetFormI18nChoiceCountry':
                $return_val = I18nUtilities::getCountry($f_value);
                break;
            case 'sfWidgetFormDoctrineChoice':
            case 'sfWidgetAutocompleteWithAdd':
            case 'sfWidgetChoiceWithAdd':
                if ($form_field->getWidget()->getOption('multiple') == true) {
                    $model = $form_field->getWidget()->getOption('model');
                    $objs = Doctrine::getTable($model)->createQuery()->whereIn('id', $f_value)->execute();

                    $tmp_ret = array();
                    foreach ($objs as $obj) {
                        $return_val[$obj->getPrimaryKey()] = __($obj->__toString());
                    }
                    $return_val = implode('، ', $return_val);
                } else {
                    $return_val = Doctrine::getTable($form_field->getWidget()->getOption('model'))->find($f_value);
                }
                break;
            case 'sfWidgetChoiceWithOther':
                if (is_numeric($f_value)) {
                    $loc = LocationsInSectorTable::getInstance()->find($f_value);
                    if (is_object($loc))
                        $return_val = $loc->getExtendedString();
                    else
                        $return_val = '';
                } else {
                    $return_val = $f_value;
                }
                break;
            case 'sfWidgetFormSelectRadio':
                $choices = $form_field->getWidget()->getChoices();
                if (isset($choices[$f_value])) {
                    $return_val = $choices[$f_value];
                }
                break;
            case 'sfWidgetFormSelect':
            case 'sfWidgetFormChoice':
                $opts = $form_field->getWidget()->getOptions();
                $choices = $opts['choices'];
                if (isset($opts['multiple']) && $opts['multiple']) {
                    $return_val = array();
                    foreach ($f_value as $val) {
                        $return_val[] = __($choices[$val]);
                    }
                    $return_val = implode('، ', $return_val);
                } else {
                    if (isset($choices[$f_value])) {
                        $return_val = __($choices[$f_value]);
                    }
                }
                break;
            case 'sfHijreeDateWidget':
                $value = $f_value;
                $value = is_array($value) ? implode('-', $value) : $value;
                $return_val = globals::getHijreeDate($value);
                break;
            case 'sfWidgetFormDate':
                $value = $f_value;
                $value = is_array($value) ? implode('-', $value) : $value;
                $return_val = __($value);
                break;
            case 'sfWidgetAjaxFileUpload':
                $files = FilesUploadedTable::getInstance()->getFilesByIds($form_field->getValue());

                $download_url = $form_field->getWidget()->getOption('download_url');
                $return_val = '';
                foreach ($files as $file_id => $file_info) {
                    $return_val .= $file_info['real_name'] . ' ' . link_to('(download)', $download_url . '?id=' . $file_info['id']) . "\n";
                }

                $return_val = str_replace("\n", "<br/>", $return_val);
                break;
            case 'sfWidgetFormJQueryAutocompleter':
                $return_val = $f_value;
                if ($func = $form_field->getWidget()->getOption('value_callback')) {
                    $return_val = call_user_func($func, $return_val);
                }
                break;
            default:
                $return_val = $f_value;
                break;
        }

        if ($return_val === '') {
            $return_val = __('N.A');
        }

        return $return_val;
    }

    /**
     * rendering the form in a show mode
     *
     * @return string form XHTML contents...
     */
    public function renderShowMode() {
        $form_formatter = $this->getWidgetSchema()->getFormFormatter();
        $return_val = '';

        foreach ($this as $name => $field) {
            if ($field instanceof sfFormFieldSchema) {
                $sub_form = $this->getEmbeddedForm($name);
                $sub_form_str = $sub_form->renderShowMode();
                $field_str = str_replace('%content%', $sub_form_str, $form_formatter->getDecoratorFormat()); // to print <table> tag automatically
            } else {
                if ($field->getWidget() instanceof sfWidgetFormInputHidden && !$field->getWidget() instanceof sfWidgetAjaxFileUpload)
                    continue;
                // skip the main currency widget from the show mode
                if ($field->getWidget() instanceof sfWidgetFormCurrency && $field->getWidget()->getOption('main_currency_field'))
                    continue;
                $field_str = self::getShowValue($field);
            }

            $label_str = '';
            if (method_exists($form_formatter, 'generateLabelForShow')) {
                $label_str = $form_formatter->generateLabelForShow($name);
            } else {
                $label_str = $form_formatter->generateLabel($name);
            }
            $return_val .= $form_formatter->formatRow($label_str, $field_str, array(), '', '');
        }

        return $return_val;
    }

}
